use chrono::{Local};
use yew::{function_component, html, use_context, Callback, Children, Html, Properties, UseReducerHandle};
use yew_hooks::{use_mount, use_websocket_with_options, UseWebSocketOptions};
use crate::business::app_state::AppState;
use crate::business::websocket::dto::rpc_data::RpcData;
use crate::business::websocket::dto::user_dto::{LoginReq, TerminalType};
use crate::business::websocket::receive_send_handle::{ImReceiveSendHandle, ImReceiveSendHandleMsg};

#[derive(Properties, Clone, PartialEq)]
pub struct ImWebSocketProps {
    pub url: String,
    pub children: Children,
    pub receive_send_handle: UseReducerHandle<ImReceiveSendHandle>,
    pub websocket_status_callback: Callback<ImWebSocketStatus>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ImWebSocketStatus {
    Connected,
    Disconnected,
}

/// 将send_data 和 receive_data合并成一个
#[function_component(ImWebSocketView)]
pub fn web_socket(props: &ImWebSocketProps) -> Html {
    let app_state = use_context::<AppState>().unwrap();

    let url = props.url.clone();

    let app_state1 = app_state.clone();
    let websocket_status_callback1 = props.websocket_status_callback.clone();
    let websocket_status_callback2 = props.websocket_status_callback.clone();
    let ws = {
        use_websocket_with_options(
            props.url.clone(),
            UseWebSocketOptions {
                // Receive message by callback `onmessage`.
                onmessage: Some(Box::new(move |message| {
                    log::info!("websocket received message: {:?}", message);
                    let websocket_handle = app_state1.receive_send_handle.clone().unwrap();
                    websocket_handle.dispatch(ImReceiveSendHandleMsg::ReceiveMessage(message));
                })),
                onopen: Some(Box::new(move |_| {
                    log::info!("websocket opened");
                    websocket_status_callback1.emit(ImWebSocketStatus::Connected);
                })),
                onclose: Some(Box::new(move |_| {
                    log::info!("websocket closed");
                    websocket_status_callback2.emit(ImWebSocketStatus::Disconnected);
                })),
                manual: Some(true),
                ..Default::default()
            },
        )
    };

    let ws_clone = ws.clone();
    let app_state4 = app_state.clone();

    let receive_send_data_clone = props.receive_send_handle.clone();
    use_mount(move || {
        log::info!("websocket opening, url: {}", url);
        ws_clone.open();

        let tt = app_state4.receive_send_handle.clone();

        log::info!("websocket opening, url: {}", tt.is_some());
        if let Some(handle) = tt {
            handle.dispatch(ImReceiveSendHandleMsg::SetUseWebSocketHandle(ws_clone));
        } else {
            receive_send_data_clone.dispatch(ImReceiveSendHandleMsg::SetUseWebSocketHandle(ws_clone));
        }
    });


    // let send_data_click = {
    //     let ws = ws.clone();
    //     Callback::from(move |_| {
    //         let login_req = LoginReq {
    //             user_id: "test00100".to_string(),
    //             password: "123456".to_string(),
    //             machine_code: "web".to_string(),
    //             tenant_code: "0000".to_string(),
    //             terminal_type: TerminalType::Web,
    //             create_date_time: Local::now(),
    //             local_seq: format!("{}_00001", Local::now().to_rfc2822()),
    //         };
    //         let rpc_data = RpcData::new("login".to_string(), login_req, format!("{}_00001", Local::now().timestamp()));
    //         let json = rpc_data.into();
    //         log::info!("login req2222225555555: {}", json);
    //         ws.send(json);
    //     })
    // };

    // let state4 = props.receive_send_data.clone();
    // let total = use_state(|| 0);
    // let total2 = total.clone();
    // use_interval(move || {
    //     log::info!("use_interval34444444444444444444, {}", state4.show_message_callback.borrow().is_some());
    //     let show_message_callback = state4.show_message_callback.borrow_mut().clone();
    //     if let Some(callback2) = show_message_callback {
    //         let new_value = (*total2) + 1;
    //         total2.set(new_value);
    //
    //         let now = Local::now();
    //         let is_send = now.timestamp() % 3 == 0;
    //         let message = ImMessage{ id: new_value, name: "demo".to_string(), content: "我可以帮你写代码、读文件、写作各种创意内容，请把你的任务交给我吧".to_string(), is_send, time: now};
    //         let t = callback2.clone();
    //         log::info!("receive message: {}", new_value);
    //         t.emit(message);
    //         log::info!("receive send message: {}", new_value);
    //     }
    // }, 2000);

    html! {
        <>
            // <button onclick={send_data_click}>{"send data:"}{app_state.clone().total}</button>
            { for props.children.iter() }
        </>
    }
}

